/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package putime.newspaperagent.stock;

import java.awt.event.ItemEvent;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import putime.model.ModelStock;

/**
 *
 * @author Khai
 */
public class frmStock extends javax.swing.JFrame {
    
    ModelStock modelStock = new ModelStock();
    Vector vSup = new Vector<>();
    Date date;

    /**
     * Creates new form frmStock
     */
    public frmStock() {
        initComponents();
        initCalendar();
    }
    
    public void initCalendar() {
        java.util.Date date = new java.util.Date();
        txtDate.setDate(date);
        layDate();
    }
    
    public void layDate() {
        SimpleDateFormat sdf = new SimpleDateFormat();
        
        try {
            date = new Date(Date.parse(sdf.format(txtDate.getDate())));
        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(this, "You must input the correct Hire Date formats: MMM d, yyyy ");
            return;
        }
        viewStock();
    }
    
    public void viewStock() {
        
        vSup = modelStock.connViewStock(date);
        DefaultComboBoxModel dcm = new DefaultComboBoxModel(vSup);
        cobSupplier.setModel(dcm);
        viewTable();
    }
    
    public void viewTable() {
        Vector vtCols = new Vector();
        Vector vData = new Vector();
        String[] colNames = new String[]{"Stock ID", "Product Name", "Product ID", "Rate", "InWard Qtys", "Returned"};
        for (String colName : colNames) {
            vtCols.add(colName);
        }
        String tam = String.valueOf(cobSupplier.getSelectedItem());
        try {
            tam = tam.substring(0, tam.indexOf(" "));
            int chon = Integer.parseInt(tam);
            vData = modelStock.connViewTable(chon, date);
        } catch (StringIndexOutOfBoundsException e) {
        }
        DefaultTableModel tblModel = new DefaultTableModel(vData, vtCols);
        tblStock.setModel(tblModel);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblStock = new javax.swing.JTable();
        txtDate = new com.toedter.calendar.JDateChooser();
        cobSupplier = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnView = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblStock.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Stock ID", "Product Name", "Product ID", "Rate", "Inward Qtys", "Returned"
            }
        ));
        jScrollPane1.setViewportView(tblStock);

        cobSupplier.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cobSupplierItemStateChanged(evt);
            }
        });

        jLabel1.setText("Stock Date");

        jLabel2.setText("Supplier");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnView.setText("View");
        btnView.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(67, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 683, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(292, 292, 292)
                            .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(22, 22, 22)
                            .addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(btnDelete)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(btnCancel)
                            .addGap(52, 52, 52)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27)
                        .addComponent(btnView)
                        .addGap(86, 86, 86)
                        .addComponent(jLabel2)
                        .addGap(40, 40, 40)
                        .addComponent(cobSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(54, 54, 54))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cobSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(btnView))
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnDelete)
                    .addComponent(btnEdit)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewActionPerformed
        layDate();
    }//GEN-LAST:event_btnViewActionPerformed
    
    private void cobSupplierItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cobSupplierItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            viewTable();
        }
    }//GEN-LAST:event_cobSupplierItemStateChanged
    
    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed
    
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        new AddStock(this, true).setVisible(true);
    }//GEN-LAST:event_btnAddActionPerformed
    
    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        int selectedRow = tblStock.getSelectedRow();
        String stockID, productName, productID, rate, inward, returned;
        String supplier = String.valueOf(cobSupplier.getSelectedItem());
        try {
            stockID = String.valueOf(tblStock.getValueAt(selectedRow, 0));
            productName = String.valueOf(tblStock.getValueAt(selectedRow, 1));
            productID = String.valueOf(tblStock.getValueAt(selectedRow, 2));
            rate = String.valueOf(tblStock.getValueAt(selectedRow, 3));
            inward = String.valueOf(tblStock.getValueAt(selectedRow, 4));
            returned = String.valueOf(tblStock.getValueAt(selectedRow, 5));
        } catch (ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "no row is selected");
            return;
        }
        
        EditStock editStock = new EditStock(this, true);
        editStock.initEditStock(date, stockID, supplier, productName, productID, rate, inward, returned);
        editStock.setVisible(true);
    }//GEN-LAST:event_btnEditActionPerformed
    
    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        int selectedRow = tblStock.getSelectedRow();
        String tam;
        int stockID = -1;
        
        try {
            tam = String.valueOf(tblStock.getValueAt(selectedRow, 0));
            stockID = Integer.parseInt(tam);
        } catch (ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "no row is selected");
            return;
        }
        int chon = JOptionPane.showConfirmDialog(this, "You want delete StockID: " + stockID);
        if (chon != 0) {
            return;
        }
        boolean kiemTra = modelStock.deleteStock(stockID);
        if (kiemTra) {
            JOptionPane.showMessageDialog(this, "Delete Successfully !!!");
            initCalendar();
        } else {
            JOptionPane.showMessageDialog(this, "Fail !!!", "Warning", 0);
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmStock().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnView;
    private javax.swing.JComboBox cobSupplier;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblStock;
    private com.toedter.calendar.JDateChooser txtDate;
    // End of variables declaration//GEN-END:variables
}
